package com.zhoug.demo.player.play;

import android.Manifest;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextUtils;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.zhoug.common.permission2.ZPermissions;
import com.zhoug.common.utils.FileUtils;
import com.zhoug.common.utils.StringUtils;
import com.zhoug.common.utils.TimeUtils;
import com.zhoug.common.utils.ToastUtils;
import com.zhoug.demo.player.Monitor;
import com.zhoug.demo.player.MonitorDialog;
import com.zhoug.demo.player.MyBaseActivity;
import com.zhoug.demo.player.http.ApiRepository;
import com.zhoug.demo.player.http.DataCallback;
import com.zhoug.demo.templete.R;
import com.zhoug.logging.Logger;
import com.zhoug.player.core.CapturePictureListener;
import com.zhoug.player.core.PlayListener;
import com.zhoug.player.core.PlayProgressListener;
import com.zhoug.player.core.VideoRecordListener;
import com.zhoug.player.core.ZPlayer;
import com.zhoug.player.core.utils.LogUtils;
import com.zhoug.player.vlcplayer.VLCPlayer;
import com.zhoug.zmui.list.OnSelectChangeListener;

import java.io.File;
import java.text.MessageFormat;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.media3.common.util.UnstableApi;


@UnstableApi
public class VlcActivity extends MyBaseActivity {
    private static final String TAG = ">>>VlcActivity";
    private TimePrinter TIME_PRINTER = new TimePrinter();

    private MonitorDialog mMonitorDialog;
    private ApiRepository mApiRepository;
    private Monitor mMonitor;
    private ZPlayer mPlayer;
    private TextureView mTextureView;
    private Button mBtnStartPlay;
    private EditText mEtUrl;
    private TextView mBtnClearUrl;
    private Button mBtnGetPlayUrl;
    private Button mBtnPausePlay;
    private Button mBtnStopPlay;
    private Button mBtnMonitor;
    private TextView mTvMonitor;
    private Button mBtnPrepare;
    private Button mBtnRelease;
    private TextView mTvPlayProgress;
    private ProgressBar mProgressBar;
    private TextView mTvError;
    private Switch mSwithRtsp;
    private ImageView mImgCover;
    private Button mBtnCapureImg;
    private Button mBtnRecord;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_vlc;
    }

    @Override
    protected void findViews() {
        mTextureView = findViewById(R.id.textureView);
        mBtnStartPlay = findViewById(R.id.btn_startPlay);
        mEtUrl = findViewById(R.id.et_url);
        mBtnClearUrl = findViewById(R.id.btn_clearUrl);
        mBtnGetPlayUrl = findViewById(R.id.btn_getPlayUrl);
        mBtnPausePlay = findViewById(R.id.btn_pausePlay);
        mBtnStopPlay = findViewById(R.id.btn_stopPlay);
        mBtnMonitor = findViewById(R.id.btn_monitor);
        mTvMonitor = findViewById(R.id.tv_monitor);
        mBtnPrepare = findViewById(R.id.btn_prepare);
        mBtnRelease = findViewById(R.id.btn_release);
        mTvPlayProgress = findViewById(R.id.tv_playProgress);
        mProgressBar = findViewById(R.id.progressBar);
        mTvError = findViewById(R.id.tv_error);
        mSwithRtsp = findViewById(R.id.swith_rtsp);
        mImgCover = findViewById(R.id.img_cover);
        mBtnCapureImg = findViewById(R.id.btn_capureImg);
        mBtnRecord = findViewById(R.id.btn_record);
    }

    private void initMonitors() {
        List<Monitor> monitors = Monitor.getMonitors();
        mMonitor = monitors.get(0);
        mTvMonitor.setText(mMonitor.getName());
        mMonitorDialog = new MonitorDialog(this);
        mMonitorDialog.setData(monitors);
        mMonitorDialog.setSelect(mMonitor);
        mMonitorDialog.setMultiSelect(false);
        mMonitorDialog.setOnSelectChangeListener(new OnSelectChangeListener<Monitor>() {
            @Override
            public void onSelectChange(@NonNull List<Monitor> select) {
                if (!select.isEmpty()) {
                    mMonitor = select.get(0);
                } else {
                    mMonitor = null;
                }
                mTvMonitor.setText(mMonitor != null ? mMonitor.getName() : "");
                if (mMonitor != null && !StringUtils.isNullOrEmpty(mMonitor.getUrl())) {
                    mEtUrl.setText(mMonitor.getUrl());
                }
            }

            @Override
            public void onClearSelect() {
                mMonitor = null;
                mTvMonitor.setText("");
            }
        });
    }

    @Override
    protected void onCreate1(Bundle savedInstanceState) {
        mApiRepository = new ApiRepository();
        mApiRepository.setLifecycleOwner(this);
        initMonitors();

        mBtnMonitor.setOnClickListener(v -> {
            mMonitorDialog.show();
        });

        mBtnGetPlayUrl.setOnClickListener(v -> {
            if (mMonitor == null) {
                ToastUtils.toastShort("请选择摄像头");
                return;
            }
            int protocol = mSwithRtsp.isChecked() ? 1 : 0;
            mApiRepository.getFirmMonitorPlayUrlById(mMonitor.getId(), protocol, new DataCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    if (StringUtils.isNullOrEmpty(s)) {
                        Logger.e(TAG, "播放地址为空");
                        ToastUtils.toastLong("播放地址为空");
                    } else {
                        Logger.d(TAG, "获取播放地址成功:" + s);
                        ToastUtils.toastShort("获取播放地址成功");
                        mEtUrl.setText(s);
                    }
                }

                @Override
                public void onFailure(String error) {
                    ToastUtils.toastLong(error);
                }
            });
        });
        mBtnClearUrl.setOnClickListener(v -> {
            mEtUrl.setText("");
        });
        mBtnStartPlay.setOnClickListener(v -> {
            String url = null;
            Editable text = mEtUrl.getText();
            if (text != null) {
                url = text.toString().trim();
            }
            if (TextUtils.isEmpty(url)) {
                Toast.makeText(this, "播放地址为空", Toast.LENGTH_LONG);
                return;
            }
            mTvPlayProgress.setText("");
            mPlayer.setPlayUrl(url);
            mPlayer.startPlay();
        });

        mBtnPausePlay.setOnClickListener(v -> {
            mPlayer.pausePlay();

        });

        mBtnPrepare.setOnClickListener(v -> {
            String url = null;
            Editable text = mEtUrl.getText();
            if (text != null) {
                url = text.toString().trim();
            }
            if (TextUtils.isEmpty(url)) {
                Toast.makeText(this, "播放地址为空", Toast.LENGTH_LONG);
                return;
            }
            mTvPlayProgress.setText("");
            mPlayer.setPlayUrl(url);
            mPlayer.startPlay();
        });


        mBtnStopPlay.setOnClickListener(v -> {
            mPlayer.stopPlay();

        });
        mBtnRelease.setOnClickListener(v -> {
            mPlayer.release();
            mTvPlayProgress.setText("");
        });

        mBtnCapureImg.setOnClickListener(v -> {
            if (mPlayer.isPlaying()) {
                ZPermissions.with(this)
                        .setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                        .setCallback((success, granted, denied) -> {
                            if (success) {
                                File externalPublicFolder = FileUtils.getExternalPublicFolder(Environment.DIRECTORY_PICTURES);
                                File folder = new File(externalPublicFolder, "imgs");
                                FileUtils.createDirectory(folder);
                                File file = new File(folder, System.currentTimeMillis() + ".png");
                                mPlayer.capturePicture(file.getAbsolutePath());
                            }
                        }).request();

            }
        });

        mBtnRecord.setOnClickListener(v -> {
            ZPermissions.with(this)
                    .setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                    .setCallback((success, granted, denied) -> {
                        if (success) {
                            File externalPublicFolder = FileUtils.getExternalPublicFolder(Environment.DIRECTORY_PICTURES);
                            File folder = new File(externalPublicFolder, "records");
                            FileUtils.createDirectory(folder);
                            File file = new File(folder, System.currentTimeMillis() + ".mp4");
                            if (mPlayer.isRecording()) {
                                mPlayer.stopRecordVideo();
                            } else {
                                mPlayer.startRecordVideo(file.getAbsolutePath());
                            }
                        }
                    }).request();

        });


        initPlayer();

//        new Timer().schedule(new TimerTask() {
//            @Override
//            public void run() {
//                if(mPlayer!=null){
//                    int state = mPlayer.getState();
//                    LogUtils.w(TAG, "state:"+state);
//                }
//            }
//        },100,100);
    }

    private void initPlayer() {
        mPlayer = new VLCPlayer(this);
        mTextureView.setKeepScreenOn(true);
        mPlayer.setVideoTextureView(mTextureView);
        mPlayer.setCapturePictureListener(new CapturePictureListener() {
            @Override
            public void onCapturePictureResult(boolean success, Bitmap bitmap, String path) {
                if (success) {
                    LogUtils.w(TAG, "截屏成功:" + "path:" + path);
                } else {
                    LogUtils.w(TAG, "截屏失败:" + "path:" + path);
                }
                if (success) {
                    ToastUtils.toastShort("截图成功");
                } else {
                    ToastUtils.toastShort("截图失败");
                }
            }
        });
        mPlayer.setVideoRecordListener(new VideoRecordListener() {
            @Override
            public void onStartRecordVideo() {
                LogUtils.w(TAG, "开始录像");
                mBtnRecord.setText("停止录像");
            }

            @Override
            public void onStopRecordVideo(String path) {
                LogUtils.w(TAG, "结束录像:"+path);
                mBtnRecord.setText("录像");
                ToastUtils.toastShort("结束录像:"+path);
            }

            @Override
            public void onErrorRecordVideo(String error) {
                LogUtils.e(TAG, "录像错误:" + error);
                ToastUtils.toastShort(error);
                mBtnRecord.setText("录像");
            }

            @Override
            public void onRecordVideoTime(int time) {
                LogUtils.w(TAG, "录像中:" + time);

            }
        });

        mPlayer.setPlayProgressListener(new PlayProgressListener() {
            private long mDuration = 0;

            @Override
            public void onDurationChange(long duration) {
                mDuration = duration;
            }

            @Override
            public void onPositionChange(long position) {
                String s1 = TimeUtils.formatSecond((int) (position / 1000));
                String s2 = TimeUtils.formatSecond((int) (mDuration / 1000));
                mTvPlayProgress.setText(MessageFormat.format("{0} / {1}", s1, s2));
            }
        });

        mPlayer.setPlayListener(new PlayListener() {
            @Override
            public void onPlayStatusChange(int state) {
                switch (state) {
                    case ZPlayer.STATE_IDLE:
                        LogUtils.w(TAG, "onPlayStatusChange:STATE_IDLE");
                        hideError();
                        hideProgress();
                        break;
                    case ZPlayer.STATE_START:
                        LogUtils.w(TAG, "onPlayStatusChange:STATE_START");
                        hideError();
                        showProgress();
                        break;
                    case ZPlayer.STATE_PREPARED:
                        LogUtils.w(TAG, "onPlayStatusChange:STATE_PREPARED");

                        showProgress();
                        break;
                    case ZPlayer.STATE_PLAYING:
                        LogUtils.w(TAG, "onPlayStatusChange:STATE_PLAYING");
//                        hideProgress();
//                        hideCover();
                        break;
                    case ZPlayer.STATE_PAUSE:
                        LogUtils.w(TAG, "onPlayStatusChange:STATE_PAUSE");

                        hideProgress();
                        break;
                    case ZPlayer.STATE_STOP:
                        LogUtils.w(TAG, "onPlayStatusChange:STATE_STOP");

                        hideProgress();
                        break;
                    case ZPlayer.STATE_ENDED:
                        LogUtils.w(TAG, "onPlayStatusChange:STATE_ENDED");

                        hideProgress();
                        break;


                }
            }

            @Override
            public void onVideoOutput() {
                hideProgress();
                hideCover();
            }

            @Override
            public void onPlayError(int code, String error) {
                showError(error);
            }
        });
    }

    private void showProgress() {
        if (mProgressBar != null && mProgressBar.getVisibility() != View.VISIBLE) {
            mProgressBar.setVisibility(View.VISIBLE);
        }
    }

    private void hideProgress() {
        if (mProgressBar != null && mProgressBar.getVisibility() != View.GONE) {
            mProgressBar.setVisibility(View.GONE);
        }
    }

    private void showError(String error) {
        if (mTvError != null) {
            mTvError.setText(error);
            mTvError.setVisibility(View.VISIBLE);
        }
    }

    private void hideError() {
        if (mTvError != null) {
            mTvError.setText("");
            mTvError.setVisibility(View.GONE);
        }
    }

    private void showCover() {
        if (mImgCover != null) {
            mImgCover.setVisibility(View.VISIBLE);
        }
    }

    private void hideCover() {
        if (mImgCover != null) {
            mImgCover.setVisibility(View.GONE);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPlayer != null) {
            mPlayer.release();
        }
    }


}

